package net.lastcoder.ifserver.route;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * auth: WenYF
 * date: 2016/10/24
 */
public class InterceptorManager {
    private static InterceptorManager instance = new InterceptorManager();

    public static InterceptorManager getInstance() {
        return instance;
    }

    private List<PacketInterceptor> messageInterceptors;

    private InterceptorManager() {
        messageInterceptors = new CopyOnWriteArrayList<>();
    }

    public void addInterceptor(PacketInterceptor interceptor) {
        if (interceptor == null) {
            throw new NullPointerException("Parameter interceptor was null.");
        }
        if (messageInterceptors.contains(interceptor)) {
            messageInterceptors.remove(interceptor);
        }
        messageInterceptors.add(interceptor);
    }

    public void addInterceptor(int index, PacketInterceptor interceptor) {
        if (index < 0 || (index > messageInterceptors.size())) {
            throw new IndexOutOfBoundsException("Index " + index + " invalid.");
        }
        if (interceptor == null) {
            throw new NullPointerException("Parameter interceptor was null.");
        }
        if (messageInterceptors.contains(interceptor)) {
            int oldIndex = messageInterceptors.indexOf(interceptor);
            if (oldIndex < index) {
                index -= 1;
            }
            messageInterceptors.remove(interceptor);
        }

        messageInterceptors.add(index, interceptor);
    }
    public void removeInterceptor(PacketInterceptor interceptor) {
        messageInterceptors.remove(interceptor);
    }
    protected List<PacketInterceptor> getMessageInterceptors() {
        return Collections.unmodifiableList(messageInterceptors);
    }

}
